import os
import random
import string
import sys
from http.server import HTTPServer, BaseHTTPRequestHandler
import threading
import socket
from pathlib import Path
from typing import Dict, Optional
import mimetypes

# 禁用标准输出和错误输出, 以防HTTP服务无法正常运行
sys.stderr = open(os.devnull, 'w')

class ImageServer(BaseHTTPRequestHandler):
    _instance = None  # 单例实例
    _lock = threading.Lock()  # 线程安全锁

    def __new__(cls, *args, **kwargs):
        """单例模式的核心实现"""
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
                    cls._instance._initialized = False
        return cls._instance

    def __init__(self, port: int = 8000, url: str = "127.0.0.1"):
        """初始化（仅执行一次）"""
        if self._initialized:
            return

        # 初始化MIME类型数据库
        mimetypes.init()
        self.port = port
        self.url = url
        self.server: Optional[HTTPServer] = None
        self.server_thread: Optional[threading.Thread] = None  # 服务器运行线程
        self.served_files: Dict[str, str] = {}  # {url_path: absolute_file_path}
        self.running = False
        self._initialized = True

    def add_image(self, image_path: str) -> str:
        """添加图片并返回访问URL"""
        # 检查图片路径是否存在
        if not os.path.exists(image_path):
            raise FileNotFoundError(f"Image not found: {image_path}")

        # 生成唯一URL路径并保留扩展名
        abs_path = os.path.abspath(image_path).replace('\\', '/')
        ext = Path(abs_path).suffix
        url_path = generate_random_string() + ext

        # 存储绝对路径
        self.served_files[url_path] = abs_path

        # 规范化URL前缀
        if not self.url.startswith(("http://", "https://")):
            self.url = f"http://{self.url}"

        return f"{self.url}:{self.port}/{url_path}"

    def start(self):
        """启动服务器（线程安全），不阻塞调用线程"""
        if self.running:
            return

        with self._lock:
            if not self.running:
                handler = self._create_handler()
                self.server = HTTPServer(("0.0.0.0", self.port), handler)
                # 创建并启动服务器线程
                self.server_thread = threading.Thread(
                    target=self._run_server,
                    daemon=True
                )
                self.server_thread.start()
                self.running = True
                print(f"Image server started at {self.url}:{self.port}")


    def stop(self):
        """停止服务器（线程安全）"""
        if self.server and self.running:
            with self._lock:
                if self.running:
                    self.server.shutdown()
                    self.server.server_close()
                    self.running = False
                    print("Server stopped")

    def _run_server(self):
        """在新线程中运行服务器的主循环"""
        if self.server:
            print("Server thread started")
            self.server.serve_forever()
            print("Server thread exited")

    def _create_handler(self):
        """创建自定义请求处理器"""
        served_files = self.served_files

        class ImageHandler(BaseHTTPRequestHandler):

            def do_GET(self):
                # 规范化路径
                path = self.path.split('?')[0].split('#')[0].lstrip('/')

                if path in served_files:
                    file_path = served_files[path]
                    try:
                        with open(file_path, 'rb') as f:
                            content = f.read()

                        # 自动检测MIME类型
                        mime_type, _ = mimetypes.guess_type(file_path)
                        mime_type = mime_type or 'application/octet-stream'

                        self.send_response(200)
                        self.send_header('Content-type', mime_type)
                        self.send_header('Content-length', str(len(content)))
                        self.end_headers()
                        self.wfile.write(content)

                    except Exception as e:
                        self.send_error(500, f"Server Error: {str(e)}")
                else:
                    self.send_error(404, "File not found")

        return ImageHandler


def generate_random_string(length=8):
    """生成随机字符串"""
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))


if __name__ == "__main__":
    # 测试单例模式和非阻塞启动
    server1 = ImageServer(port=14786, url="home.chatzen.top")
    server2 = ImageServer(port=9999)  # 这个端口设置会被忽略

    print(f"Are instances the same? {server1 is server2}")  # 输出 True

    server1.start()  # 这个调用不会阻塞主线程

    print("Server started in a separate thread.")
    # 添加图片
    img_url = server1.add_image(r"E:/123pan/1818068532/123同步文件夹/P站图片/123629212_p0.jpg")
    img_url2 = server1.add_image(r"E:/123pan/1818068532/123同步文件夹/P站图片/{CDC876A6-8B93-419f-AB4F-E23B7D9631AE}.png")
    img_url3 = server1.add_image(r"E:/123pan/1818068532/123同步文件夹/P站图片/124309166_p0.jpg")
    print(f"Image URL: {img_url}")
    print(f"Image URL 2: {img_url2}")
    print(f"Image URL 3: {img_url3}")

    # 主线程可以继续执行其他任务
    print("Main thread continues to run...")

    try:
        # 模拟主线程工作
        while True:
            user_input = input("Enter 'stop' to stop server or 'exit' to quit: ")
            if user_input.lower() == 'stop':
                server1.stop()
            elif user_input.lower() == 'exit':
                server1.stop()
                break
    except KeyboardInterrupt:
        server1.stop()